package com.unidt.dbutils;

import com.unidt.conf.ConfFactory;
import com.unidt.conf.IConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;
import java.util.List;

public class MySQL implements IDataBase {

    private Connection conn = null;
    private Logger log = LoggerFactory.getLogger(MySQL.class);

    public void connect()throws Exception {

        Class.forName("com.mysql.jdbc.Driver");

        IConf conf = ConfFactory.createPropertyConfig("db.properties");

        String host = conf.getString("host");
        String port = conf.getString("port");
        String username = conf.getString("username");
        String dbname = conf.getString("dbname");
        String pwd = conf.getString("password");
        String url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;

        log.info("连接URL：" + url);
        conn = DriverManager.getConnection(url, username, pwd);

    }
    /**
     * 执行SQL语句
     * @param sql
     */
    public void executeQuery(String sql) {
        try {
            Statement st = conn.createStatement();
            ResultSet ret = st.executeQuery(sql);
            if (ret.next()) {
                System.out.println(ret.getString(1));
            }
            ret.close();
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void executeBatch(List<String> sql) {
        try {
            Statement st = conn.createStatement();
            for (String cmd: sql) {
                st.addBatch(cmd);
            }
            st.executeBatch();
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        MySQL sql = new MySQL();
        sql.connect();
        sql.executeQuery("select * from final_tag_4");
        sql.close();
    }
}
